package com.huiyujiaoyu.powertime.ui.find;


import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huiyujiaoyu.base.AppContext;
import com.huiyujiaoyu.base.BaseFragment;
import com.huiyujiaoyu.http.HttpApi;
import com.huiyujiaoyu.http.HttpMethods;
import com.huiyujiaoyu.powertime.R;
import com.huiyujiaoyu.powertime.model.IndexItemModel;
import com.huiyujiaoyu.powertime.model.SimpleListBean;
import com.huiyujiaoyu.powertime.ui.home.ArticleDetailsActivity;
import com.huiyujiaoyu.powertime.ui.home.SearchActivity;
import com.huiyujiaoyu.powertime.ui.home.ShiPinDetailActivity;
import com.huiyujiaoyu.powertime.ui.home.VoiceDetailActivity;
import com.huiyujiaoyu.util.ActivityUtil;
import com.huiyujiaoyu.util.AnimatorUtil;
import com.huiyujiaoyu.util.Constant;
import com.huiyujiaoyu.util.GlideUtil;
import com.huiyujiaoyu.util.StringUtils;
import com.huiyujiaoyu.widget.CustomLoadMoreView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 首页
 * Created by yujunlong on 2016/12/5.
 */

public class FindFragment extends BaseFragment {

    @BindView(R.id.ll_search)
    LinearLayout mLlSearch;
    @BindView(R.id.ibtn_xiaoxi)
    ImageButton mIbtnXiaoxi;
    @BindView(R.id.fl_msg)
    FrameLayout mFlMsg;
    @BindView(R.id.rl_score)
    RelativeLayout mRlScore;
    @BindView(R.id.tv_status)
    TextView mTvStatus;
    @BindView(R.id.iv_status)
    ImageView mIvStatus;
    @BindView(R.id.ll_all)
    LinearLayout mLlAll;
    @BindView(R.id.ll_filter_bar)
    LinearLayout mLlFilterBar;
    @BindView(R.id.xr_view)
    RecyclerView mXrView;
    @BindView(R.id.iv_show)
    ImageView mIvShow;
    @BindView(R.id.lv_options)
    RecyclerView mLvOptions;
    @BindView(R.id.ll_filter_content)
    LinearLayout mLlFilterContent;
    @BindView(R.id.fl_content)
    FrameLayout mFlContent;
    @BindView(R.id.swipe)
    SwipeRefreshLayout mSwipe;
    @BindView(R.id.rb_content)
    RadioGroup rb_content;
    private boolean isAlert; //左侧的筛选是否弹出， 默认没有
    private BaseQuickAdapter<IndexItemModel, BaseViewHolder> adapetr2, adapter;

    private List<IndexItemModel> datas,fenledatas;
    private int page, dict_key,content_type;

    public static FindFragment newInstance() {
        Bundle args = new Bundle();
        FindFragment fragment = new FindFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_find;
    }

    @Override
    protected void userBundle(Bundle savedInstanceState) {
        super.userBundle(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleNoBar();
        datas = new ArrayList<>();
        adapter = new BaseQuickAdapter<IndexItemModel, BaseViewHolder>(R.layout.cell_find_content, datas) {
            @Override
            protected void convert(BaseViewHolder helper, IndexItemModel item) {
                TextView tvzj = helper.getView(R.id.tv_item_zhangjie);
                ImageView contype1 = helper.getView(R.id.iv_item_contype2);
                ImageView contype2 = helper.getView(R.id.iv_item_contype);
                ImageView iv_item_status = helper.getView(R.id.iv_item_status);
                helper.setText(R.id.tv_item_title, item.title);
                helper.setText(R.id.tv_author, item.author_name);
                helper.setText(R.id.tv_read_count, item.view_count + "");
                helper.setText(R.id.tv_comment_count, item.comment_count + "");
                tvzj.setText("共" + item.chapter_count + "节");
                tvzj.setVisibility(item.content_type == 1 ? View.INVISIBLE : View.VISIBLE);
                GlideUtil.loadCircleImg((ImageView) helper.getView(R.id.iv_item_touxiang), StringUtils.getFullUrl(item.author_photo));
                GlideUtil.loadImg((ImageView) helper.getView(R.id.iv_pic), StringUtils.getFullUrl(item.cover));
                contype1.setImageResource(StringUtils.getResId2(item.content_type));
                contype2.setImageResource(StringUtils.getResId2(item.content_type));
                if (item.status == 2) {
                    iv_item_status.setVisibility(View.INVISIBLE);
                } else {
                    iv_item_status.setVisibility(View.VISIBLE);
                    iv_item_status.setImageResource(StringUtils.getResId(item.status));
                }

            }
        };
        mXrView.setLayoutManager(new LinearLayoutManager(mContext));
        mXrView.setHasFixedSize(true);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        mXrView.setAdapter(adapter);
        mSwipe
                .setColorSchemeResources(R.color.blue_,
                        R.color.blue_, R.color.blue_,
                        R.color.blue_);
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mXrView);
        if (AppContext.datas.size() > 0) {
            setData();
        } else {
            HttpMethods.getInstance().column(mContext, getComp(), this, "0");
        }
        mSwipe.setRefreshing(true);
        refresh();
    }


    @Override
    protected void initListener() {
        super.initListener();
        mXrView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexItemModel indexItemModel = datas.get(position);
                switch (indexItemModel.content_type) {
                    case Constant.CONTENT_TYPE_YP:
                        VoiceDetailActivity.launch(mContext,indexItemModel.content_id+"");
                        break;
                    case Constant.CONTENT_TYPE_SP:
                        ShiPinDetailActivity.launch(mContext,indexItemModel.content_id+"");
                        break;
                    case Constant.CONTENT_TYPE_WZ:
                        ArticleDetailsActivity.launch(mContext,indexItemModel.content_id+"");
                        break;
                }
            }
        });
        rb_content.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_all:
                        content_type = Constant.CONTENT_TYPE_ALL;
                        mSwipe.setRefreshing(true);
                        refresh();
                        break;
                    case R.id.rb_shipin:
                        content_type = Constant.CONTENT_TYPE_SP;
                        mSwipe.setRefreshing(true);
                        refresh();
                        break;
                    case R.id.rb_yinpin:
                        content_type = Constant.CONTENT_TYPE_YP;
                        mSwipe.setRefreshing(true);
                        refresh();
                        break;
                    case R.id.rb_wenzhang:
                        content_type = Constant.CONTENT_TYPE_WZ;
                        mSwipe.setRefreshing(true);
                        refresh();
                        break;
                }
            }
        });
    }

    @OnClick({R.id.ll_all, R.id.iv_show, R.id.ll_search, R.id.ibtn_xiaoxi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_all:
                if (!isAlert) {
                    isAlert = true;
                    mIvShow.setVisibility(View.VISIBLE);
                    mIvStatus.setImageResource(R.mipmap.discover_jiantou_xia);
                    AnimatorUtil.animateOpen(mContext, mLlFilterContent);
                }
                break;
            case R.id.iv_show:
                if (isAlert) {
                    isAlert = false;
                    mIvShow.setVisibility(View.GONE);
                    mIvStatus.setImageResource(R.mipmap.discover_jiantou_shang);
                    AnimatorUtil.animateClose(mContext, mLlFilterContent);
                }

                break;
            case R.id.ibtn_xiaoxi:

                break;
            case R.id.ll_search:
                ActivityUtil.startActivity(mContext, SearchActivity.class);
                break;

        }


    }

    public void setData() {
        fenledatas = new ArrayList<>();
        fenledatas.addAll(AppContext.datas);
        fenledatas.get(0).isOk = true;
        adapetr2 = new BaseQuickAdapter<IndexItemModel, BaseViewHolder>(R.layout.cell_find_fileter, fenledatas) {
            @Override
            protected void convert(BaseViewHolder helper, IndexItemModel item) {
                TextView tv = helper.getView(R.id.tv_content);
                tv.setText(item.dict_value);
                tv.setSelected(item.isOk);
            }
        };
        mLvOptions.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexItemModel indexItemModel = fenledatas.get(position);
                dict_key = indexItemModel.dict_key;
                setSelectPos(position);
            }
        });
        mLvOptions.setLayoutManager(new LinearLayoutManager(mContext));
        mLvOptions.setAdapter(adapetr2);
        dict_key = 0;
    }

    public void setSelectPos(int pos) {
        int size = fenledatas.size();
        for (int i = 0; i < size; i++) {
            fenledatas.get(i).isOk = i == pos;
        }
        adapetr2.notifyDataSetChanged();
        mSwipe.setRefreshing(true);
        refresh();
    }

    @Override
    public void onNext(Object o, int httpcode) {
        super.onNext(o, httpcode);
        switch (httpcode) {
            case HttpApi.HTTP_COL_INDEX:
                SimpleListBean bean = (SimpleListBean) o;
                if (AppContext.datas.size() == 0) {
                    IndexItemModel modle = new IndexItemModel();
                    modle.dict_key = 0;
                    modle.dict_value = "全部分类";
                    AppContext.datas.add(modle);
                    AppContext.datas.addAll(bean.dict);
                }
                setData();
                break;
            case HttpApi.HTTP_FIND:
                bean = (SimpleListBean) o;
                doData(bean);
                break;
        }
    }

    private void getData() {
        HttpMethods.getInstance().find(mContext, getComp(), this, dict_key + "", content_type+"",page);
    }

    private void loadMore() {
        if (mSwipe.isEnabled()) {
            mSwipe.setEnabled(false);
        }
        page++;
        getData();
    }

    private void refresh() {
        if (mContext == null)
            return;
        if (adapter == null) {
            return;
        }
        if (adapter.isLoadMoreEnable()) {
            adapter.setEnableLoadMore(false);
        }
        page = 1;
        getData();
    }

    public void doData(SimpleListBean data) {
        if (page == 1) {
            datas.clear();
            // 设置加载更多能用
            if (mSwipe.isRefreshing()) {
                mSwipe.setRefreshing(false);
            }
            datas.addAll(data.list);
            adapter.notifyDataSetChanged();
            adapter.setEnableLoadMore(true);
            Log.e(TAG, "page == 1");
        } else {
            if (data.list == null || data.list.size() == 0) {
                adapter.loadMoreEnd();
            } else {
                datas.addAll(data.list);
                adapter.notifyDataSetChanged();
                adapter.loadMoreComplete();
            }
            if (!mSwipe.isEnabled())
                mSwipe.setEnabled(true);
            Log.e(TAG, "page != 1");
        }
        Log.e(TAG, "page==" + page);
    }
}
